import cp from 'child_process';
import path from 'path';
import  './threadCore.js';

async function threadEncryptFiles(filePathList: string[], inputPath: string, outPutPath: string, passWorld: string, progressFunc: Function | null, threadNum = 5) {
    let optionObj = {
        index: 0,
        inputPath,
        outPutPath,
        passWorld,
        progressLength: filePathList.length
    };

    // threadRunNum 在 0 ~ 10
    let threadRunNum = Number(threadNum) ? threadNum : 5;
    threadRunNum = threadRunNum < 0 ? 5 : threadRunNum;
    threadRunNum = threadRunNum > 10 ? 10 : threadRunNum;


    // 开启多线程解析文件列表，将解析成果暂时放入 缓存文件中
    const batchDataList = group(filePathList, threadRunNum);
    const resData = await Promise.all(batchDataList.map(batchData => creatThread('线程1', batchData, progressFunc, optionObj)));

    return resData.flat(2);
}


function creatThread(threadName: string, threadPathList: any[], progressFunc: Function | null, optionObj: any = {}) {
    return new Promise(function (resolve) {
        let n = cp.fork(path.join(__dirname, './threadCore.js'));

        // 向子进程发送数据
        n.send({ threadName, threadPathList, inputPath: optionObj.inputPath, outPutPath: optionObj.outPutPath, passWorld: optionObj.passWorld });

        n.on('message', function (reData: any) {
            let message = reData.message;
            switch (message) {
                case 'Progress': {
                    optionObj.index += reData.data;
                    typeof progressFunc === 'function' && progressFunc({
                        status: 'Progress',
                        description: '【开启 5 进程加密文件】',
                        completed: optionObj.index,
                        total: optionObj.progressLength
                    });
                }
                    break;
                case 'Complete': {
                    resolve({ status: 'Complete' });
                    n.disconnect();
                }
            }
        });

    });
}


// 把完整数组分成 coreNum 份，数组平分
function group(array: any[], subNum: number) {
    let part = (array.length / subNum) + 1;
    let newArray = [];
    for (let i = 0; i < subNum; i++) {
        newArray.push(array.slice(i * part, (i + 1) * part));
    }

    return newArray;
}

export default threadEncryptFiles;

